package com.liu.user.service;

import com.liu.common.entity.PageResult;
import com.liu.common.status.CodeEnum;
import com.liu.common.status.RedisKeyEnum;
import com.liu.common.utils.IdWorker;
import com.liu.user.dao.UserDao;
import com.liu.user.entity.User;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2019/8/15 0015.
 * @service  用来标准他是一个service层的实现类
 * @Slf4j  用来生成一个log的内置对象，这样我们就可以使用log 来记录日志
 *
 */
@Service
@Slf4j
@Transactional
public class UserService {

    @Autowired
    private RedisTemplate redisTemplate ;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private UserDao userDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private BCryptPasswordEncoder encoder;



    public User findById(String id){

       User user = (User) redisTemplate.opsForValue().get("user_"+id);
       if(user ==null){
           log.info("缓存中无数据 {}",user);
           user =userDao.findById(id).get();
           redisTemplate.opsForValue().set("user_"+id,user);
       }

        return user;
    }

    public PageResult findAllByPage(int page, int rows, String query){
        Pageable pageable= PageRequest.of(page-1,rows);
        log.info("query:{}",query);
        Page<User> users = userDao.findSearch(query,pageable);
        log.info("{}",users.getContent());

        return new PageResult(users.getTotalElements(),users.getContent());
    }


        public void sendSMS(String mobile){




            String random =RandomStringUtils.randomNumeric(6);
            log.info("验证码为：{}",random);

            redisTemplate.boundHashOps(RedisKeyEnum.CAPTCHA_CODE.getKey()).put(mobile,random);//保存验证码到redis
            Map map = new HashMap<>();
            map.put("code",random);
            map.put("mobile",mobile);
            rabbitTemplate.convertAndSend("CAPTCHA_CODE",map); //发送验证码到rabbitmq

        }


        public void addUser(User user, String code) {


            String syscode = (String) redisTemplate.boundHashOps(RedisKeyEnum.CAPTCHA_CODE.getKey()).get(user.getMobile());
            if (syscode ==null){
                throw new RuntimeException("请点击获取短信验证码");
            }
             if(!syscode.equals(code)){
                throw  new RuntimeException("您输入的验证码不正确，请确认后重新输入");
             }
             user.setId(idWorker.nextId()+"");

             user.setPassword(encoder.encode(user.getPassword()));
             userDao.save(user);


        }

        public User findByMobileAndPassword(String mobile,String password){
            User  user = userDao.findByMobile(mobile);
            if(user!=null && encoder.matches(password,user.getPassword())){
                return  user;

            }else {
                return  null;
            }
        }

    /**
     * 添加更新粉丝数量
     * @param userid
     * @param x
     */
    public void incFanscount(String userid,int x){

        userDao.incFanscount(userid,x);

    }

    /**
     *  g更新关注数
     * @param userid
     * @param x
     */
    public void incFollowcount(String userid,int x){
      userDao.incFollowcount(userid, x);
    }
}
